package com.ruoyi.common.office;

import java.io.*;
import java.net.URL;

public class SavePPTXFromRemoteUrl {
    public static void readRemoteFileUrl(String remoteUrl,String savePath){
        try {
            URL url = new URL(remoteUrl);
            // 打开输入流（远程文件）
            try (BufferedInputStream in = new BufferedInputStream(url.openStream());
                 FileOutputStream out = new FileOutputStream(savePath)) {

                byte[] buffer = new byte[1024];
                int bytesRead;
                // 读取并写入本地文件
                while ((bytesRead = in.read(buffer)) != -1) {
                    out.write(buffer, 0, bytesRead);
                }
                System.out.println("远程文件下载完成，保存至：" + savePath);
            }
            String targetFilePath = "target.pptx";
            try (BufferedInputStream in = new BufferedInputStream(url.openStream());
                 FileOutputStream fos = new FileOutputStream(targetFilePath);
                 BufferedOutputStream bos = new BufferedOutputStream(fos)) {
                // 用 BufferedOutputStream 进一步优化写入效率
                {
                    byte[] buffer = new byte[1024]; // 缓冲区大小（1KB）
                    int bytesRead;

                    // 从源文件读取数据，写入目标文件
                    while ((bytesRead = in.read(buffer)) != -1) {
                        // 将读取到的字节写入目标文件（注意：只写入实际读取的长度 bytesRead）
                        bos.write(buffer, 0, bytesRead);
                    }
                    // 强制刷新缓冲区（确保数据写入磁盘）
                    bos.flush();
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
